package com.github.m6d21.conflict.listener;

import com.github.m6d21.conflict.config.ConflictScanConfigReader;
import com.github.m6d21.conflict.config.ConflictScanConfigReader.ScanConfig;
import com.github.m6d21.conflict.util.ConflictScanHelper;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.reflections.util.ClasspathHelper;

/**
 *<p>
 *类冲突扫描监听器
 *</p>
 *
 * @author liuyang
 * @date 2018/12/12 Wed 10:02:00
 * @since 1.0.0
 */
@WebListener(value = "conflictScanListener")
public class ConflictScanListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ConflictScanConfigReader reader = ConflictScanConfigReader.getInstance();

        ServletContext servletContext = sce.getServletContext();
        ConflictScanHelper helper = ConflictScanHelper.getInstance();
        helper.urls(ClasspathHelper.forWebInfLib(servletContext))
            .urls(ClasspathHelper.forWebInfClasses(servletContext));

        //扫描配置文件
        ScanConfig config = reader.getScanConfig();

        //注入配置
        if (config.getScanPackages() != null) {
            helper.forPackages(config.getScanPackages());
        }
        if (config.getOnlyShowDiffClass() != null) {
            helper.onlyShowDiffClass(config.getOnlyShowDiffClass());
        }
        String[] includeKeyword = null;
        if (config.getIncludeKeyword() != null) {
            includeKeyword = config.getIncludeKeyword();
        }
        String[] excludeKeyword = null;
        if (config.getExcludeKeyword() != null) {
            excludeKeyword = config.getExcludeKeyword();
        }
        if (includeKeyword != null || excludeKeyword != null) {
            helper.filter(includeKeyword, excludeKeyword);
        }
        //开始扫描
        helper.startScanConflict();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
